<?php
/**
 * Created by PhpStorm.
 * User: lh
 * Date: 2020/1/20
 * Time: 11:55
 */

namespace App\Services\Com;


use App\Models\Common\City;

class CityService
{
    /**
     * 获取指定城市对应层级所有城市id
     * @param $cityId
     * @param $level  2省  3市  4区
     * @return mixed
     * @throws \Exception
     */
    public static function getCityIds($cityId, $level = 3){
        try {
            $city = City::find($cityId);
            if(empty($city)) return[$cityId];

            $pathArr = explode(':', $city->paths);

            //当城市级别小于所传城市等级时
            if($city->level <= $level){
                $key = $city->level - 2;
            }else{
                $key = $level - 2;
                if(!isset($pathArr[$key])) throw new \Exception('该城市对应城市id集合为空');
            }

            return City::where('paths', 'like', "%{$pathArr[$key]}%")->pluck('id')->toArray();
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }
}